package com.es.stack;



/**
 * @author 二十
 *  <- 1 2 3 4 5 <-
 */
public class ArrayStack<E> extends AbstractStack<E>{

    private E [] data;

    private int size;

    public ArrayStack(int capacity){
        data = (E[]) new Object[capacity];
    }

    @Override
    public void push(E e) {
        if (size==data.length){
            resize(data.length*2);
        }
        data[size++]=e;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            throw new IllegalArgumentException("Empty stack!");
        }
        E ret = data[0];
        for (int i = 1; i <size ; i++) {
            data[i-1] = data[i];
        }
        size--;
        if (size*4 ==data.length &&  data.length/2 !=0){
            resize(data.length/2);
        }
        return ret;
    }

    @Override
    public E peek() {
        return data[0];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    private void resize(int capacity){

        E [] array = (E[]) new Object[capacity];

        for (int i = 0; i < size; i++) {
            array[i]=data[i];
            data[i]=null;
        }
        data=array;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("Stack:[");
        for (int i = 0; i < size; i++) {
            sb.append(data[i]);
            if (i!=size-1){
                sb.append("<-");
            }
        }
        return sb.append("]").toString();
    }
}
